package com.infocollect.project.api.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.infocollect.project.api.entity.*;
import com.infocollect.project.api.mapper.*;
import com.infocollect.project.api.service.*;
import com.infocollect.project.api.service.*;
import com.infocollect.project.api.vo.ApproveEntity;
import com.infocollect.project.api.vo.CopyUserEntity;
import com.infocollect.project.api.vo.ProcInstHandleEntity;
import com.infocollect.project.api.entity.*;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;

public class ProcessHelper {
    ProcInstHandleEntity Instance;
    List<ApproveEntity> dataList = new ArrayList<>();
    //@Autowired
    private ITappPorcessinsService tappPorcessinsDao;

    // @Autowired
    private ITappFromDataService tappFromdataDao;

    // @Autowired
    private ITappActinsService tappActinsService;

    //  @Autowired
    private ITappProcAuditService tappProcauditDao;

    // @Autowired
    private ITappActinsCommunicateService tappActinscommunicateDao;

    public ProcessHelper(ProcInstHandleEntity processInstance, ITappPorcessinsService tappporcessinsdao, ITappFromDataService tappfromdatadao, ITappActinsService tappactinsdao, ITappProcAuditService tappprocauditdao, ITappActinsCommunicateService tappactinscommunicatedao) {
        Instance = processInstance;
        this.tappPorcessinsDao = tappporcessinsdao;
        this.tappFromdataDao = tappfromdatadao;
        this.tappActinsService = tappactinsdao;
        this.tappProcauditDao = tappprocauditdao;
        this.tappActinscommunicateDao = tappactinscommunicatedao;
    }

    Boolean isHandled = false;
    Boolean IsFlowEnd = false;///流程是否结束

    public Boolean SaveProcInfo() {
        Instance.addRunlog("进入审批，发起 最后保存数据方法\r\n");
        SaveProcInstData(2);
        if (Instance.getActinsid() == 0) {
            isHandled = true;
        } else if ("驳回".equals(Instance.getActionname())) { ///不过多少个人审批 只要一个人驳回 流程就驳回
            isHandled = true;
            TappActinsEntity actInsEnt = tappActinsService.queryById(Instance.getActinsid());
            actInsEnt.setFstatus(2);
            actInsEnt.setFcompleteddate(new Date());
            Add(actInsEnt, "edit", "TappActins");
            List<TappActinsEntity> tappActinsList = tappActinsService.GetNotHandleActIns(Instance.getProcinsid(), Instance.getCurrentactentity().getFid());
            for (int i = 0; i < tappActinsList.size(); i++) {
                TappActinsEntity itemactins = tappActinsList.get(i);
                Add(itemactins, "del", "TappActins");
            }
        } else {
            TappActinsEntity actInsEnt = tappActinsService.queryById(Instance.getActinsid());
            actInsEnt.setFstatus(2);
            actInsEnt.setFcompleteddate(new Date());
            Add(actInsEnt, "edit", "TappActins");
            if (Instance.getCurrentactentity().getFhandletype().equals("1")) {  ///节点处理 一个人审批通过就通过
                isHandled = true;
                List<TappActinsEntity> tappActinsList = tappActinsService.GetNotHandleActIns(Instance.getProcinsid(), Instance.getCurrentactentity().getFid());
                for (int i = 0; i < tappActinsList.size(); i++) {
                    TappActinsEntity itemactins = tappActinsList.get(i);
                    Add(itemactins, "del", "TappActins");
                }
            } else { ////节点会签
                List<TappActinsEntity> tappActinsList = tappActinsService.GetAllCurrentActIns(actInsEnt.getFarrivaldate(), Instance.getProcinsid(), Instance.getCurrentactentity().getFid());
                int wait = 0;
                for (int i = 0; i < tappActinsList.size(); i++) {
                    TappActinsEntity itemactins = tappActinsList.get(i);
                    //新增判断该待办是否有效，有效待办才计算；
                    //并行会签时,FInitStatus = 1;
                    //串行会签时,FInitStatus = -1;
                    if ((itemactins.getFstatus() == 1||itemactins.getFstatus() == -1) && !itemactins.getFid().equals(actInsEnt.getFid())) {
                        wait = wait + 1;
                    }
                }
                switch (Instance.getCurrentactentity().getFhandlecountersigntype()) {
                    case "1"://所有审批通过
                        if (wait > 0) {
                            //大于0表示还有需要审批的待办才能结束
                            isHandled = false;
                        } else {
                            isHandled = true;
                        }
                        break;
                    case "2"://多数审批通过
                        double iRs = (double) (tappActinsList.size()) / 2;
                        int LeastNum = (int) (iRs + 0.5);
                        if (wait < LeastNum) //待办数小于已办数
                        {
                            isHandled = true;

                        } else {
                            isHandled = false;
                        }
                        break;
                    case "3": ///任意一个审批通过
                        isHandled = true;

                        break;
                    default:
                        isHandled = true;

                        break;
                }
                if (isHandled) {
                    for (int i = 0; i < tappActinsList.size(); i++) {
                        TappActinsEntity itemactins = tappActinsList.get(i);
                        //新增判断该待办是否有效，有效待办才计算；
                        //并行会签时,FInitStatus = 1;
                        //串行会签时,FInitStatus = -1;
                        if ((itemactins.getFstatus() == 1||itemactins.getFstatus() == -1) && itemactins.getFid() != actInsEnt.getFactid()) {
                            Add(itemactins, "del", "TappActins");
                        }
                    }
                }
            }
        }
        if (isHandled) {
            if (Instance.getNextactchartid().equals("F_End")) ///判断流程是否处理完成
            {
                IsFlowEnd = true;
                // SaveProcInstCompletedData(procInstanceEntity);
            } else {
                Instance.addRunlog("当前节点处理完成,开始插入待办数据。\r\n");
                InsertActIns(); //保存下一节点实例信息 产生待办
            }
            //   systemCC(procInstanceEntity, resolve); 保存抄送人
//                EmailHelper emial = new EmailHelper(procInstanceEntity, resolve, dataList);
//                emial.SendEmial();
            Instance.addRunlog("插入待办数据完成。\r\n");

        } else {
            if (Instance.getCurrentactentity().getFhandlecountersigntype().equals("2")) {
                Instance.addRunlog("当前节点如果为多人串行审批，需要将下一个人的审批的人待办显示出来。\r\n");
                TappActinsEntity actInsEnt = tappActinsService.queryById(Instance.getActinsid());
                List<TappActinsEntity> tappActinsList = tappActinsService.GetNotHandleCountersignActIns(actInsEnt.getFarrivaldate(), Instance.getProcinsid(), Instance.getCurrentactentity().getFid());
                if (tappActinsList.size() > 0) {
                    actInsEnt = tappActinsList.get(0);
                    actInsEnt.setFstatus(1);
                    Add(actInsEnt, "edit", "TappActins");//new ApproveEntity { Entity = actInsEnt, OperationType = "edit", TableName = "TB_WMP_ActIns" });
                } else {
                    Instance.addRunlog("没有找到下一个人的审批的人待办节点。当前节点:" + Instance.getActinsid() + "\r\n");
                }
//                    systemCC(procInstanceEntity, resolve);
                Instance.addRunlog("保存抄送。当前节点:" + Instance.getActinsid() + "\r\n");
//                    EmailHelper emial = new EmailHelper(procInstanceEntity, resolve, dataList);
//                    emial.SendEmial();
            }
        }
        return SaveData();
    }

    void Add(Object obj, String operationtype, String tablename) {
        ApproveEntity approveEntity = new ApproveEntity();
        approveEntity.setEntity(obj);
        approveEntity.setOperationtype(operationtype);
        approveEntity.setTablename(tablename);
        dataList.add(approveEntity);
    }

    /// <summary>
    /// 插入待办数据
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    /// <param name="resolve">审批对象</param>
    /// <returns></returns>
    List<String> userList = new ArrayList<>();

    public boolean InsertActIns() {
        String users = Instance.getApprovalobject().replace(';', ',');
        String[] strUser = users.split(",");
        //added by zhong 去掉重复用户
        for (Integer i = 0; i < strUser.length; i++) {
            if (strUser[i].length() > 0 && !userList.contains(strUser[i].trim())) {
                userList.add(strUser[i].trim());
            }
        }
        Date arrivaldate = new Date();
        int iCount = 0;
        for (int i = 0; i < userList.size(); i++) {
            if ("2".equals(Instance.getNexact().getFhandlecountersigntype()) )  ///串行会签
            {
                if (iCount == 0) {
                    InsertActIns(userList.get(i), 1, i, arrivaldate);
                    iCount++;
                } else
                    InsertActIns(userList.get(i), -1, i, arrivaldate);

            } else {
                InsertActIns(userList.get(i), 1, i, arrivaldate);
            }
        }
        return true;
    }

    void InsertActIns(String user, int FStatus, int index, Date arrivaldate) {
        TappActinsEntity actIns = new TappActinsEntity();
        actIns.setFid(IdWorker.getId());
        //actIns.FProcInsID = procInstanceEntity.ProcInsID.Value;
        actIns.setFactid(Instance.getNexact().getFid());//= actEnt.FID;
        //actIns.setFActName = actEnt.FActName;
        // actIns.FActType = (int)type;
        actIns.setFapproversuser(user);/// = GetAppLicense(user, procInstanceEntity, actIns.FID);  代理功能后续再实现
        actIns.setFlastupdateby(Instance.getCureentuser().getUserName());
        actIns.setFlastupdatedate(new Date());
        actIns.setFprocessid(Instance.getProcid());
        actIns.setFactchartid(Instance.getNexact().getFactchartid());
        actIns.setFarrivaldate(new Date());// = DateTime.Now;
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, index);
        actIns.setFcreationdate(nowTime.getTime()); ///= DateTime.Now.AddSeconds(index);//给创建时间加上多少秒 方便多人串行会签时，按照配置人的顺序审批
        actIns.setFcreateby(Instance.getCureentuser().getUserName()); //= procInstanceEntity.CureentUserID;
        ///  actIns.FActDisplayName = actEnt.FActDisplayName;
//        if (!string.IsNullOrEmpty(procInstanceEntity.ApprovedCallBack))
//            actIns.FAfterCallBackUrl = procInstanceEntity.ApprovedCallBack;
//        if (!string.IsNullOrEmpty(procInstanceEntity.OldApprovedCallBack))
//            actIns.FAfterCallBackUrl = procInstanceEntity.OldApprovedCallBack;
//        if (!string.IsNullOrEmpty(procInstanceEntity.MobileApprovedCallBack))
//            actIns.FAfterCallBackUrl = procInstanceEntity.MobileApprovedCallBack;
//        if (FInitStatus != 0)
//            actIns.FInitStatus = FInitStatus;
//        else
//            actIns.FInitStatus = 0;
        actIns.setFstatus(FStatus); //
        Add(actIns, "add", "TappActins");
    }

    /// <summary>
    /// 保存流程实例数据
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    /// <param name="status">流程状态</param>
    /// <returns></returns>
    public Boolean SaveProcInstData(int status) {

        // Guid gProcInsID = procInstanceEntity.ProcInsID == null ? Guid.Empty : procInstanceEntity.ProcInsID.Value;
        if (Instance.getProcinsid() == null || Instance.getProcinsid() == 0) {
            TappFromDataEntity formDataEntity = new TappFromDataEntity();
            formDataEntity.setFromid(Instance.getFromid());
            formDataEntity.setFromdata(Instance.getFromdataJson());
            formDataEntity.setFid(IdWorker.getId());
            Instance.setFforminsid(formDataEntity.getFid());
            formDataEntity.setFcreateby(Instance.getCureentuser().getUserName());// = procInstanceEntity.CureentUserID;
            formDataEntity.setFcreationdate(new Date()); ///= DateTime.Now;
            formDataEntity.setFlastupdateby(Instance.getCureentuser().getUserName());
            formDataEntity.setFlastupdatedate(new Date()); //= DateTime.Now;
            Add(formDataEntity, "add", "TappFromdata");
            TappPorcessinsEntity procInst = new TappPorcessinsEntity();
            procInst.setFid(IdWorker.getId());
            Instance.setProcinsid(procInst.getFid());
            procInst.setFcreateby(Instance.getCureentuser().getUserName());
            procInst.setFcreationdate(new Date());
            procInst.setFromdataid(formDataEntity.getFid());
            procInst.setFprocessid(Instance.getProcid());
            procInst.setFromid(Instance.getFromid());
            procInst.setFstarttime(new Date()); ///= DateTime.Now;
            procInst.setFstatus(status);
            procInst.setFstarter(Instance.getCureentuser().getUserName());// = procInstanceEntity.ApplicantUserNo;
            procInst.setFstartername(Instance.getCureentuser().getRealaname());
            procInst.setFapplicantuser(Instance.getApplicantuserno());
            procInst.setFapplicantusername(Instance.getApplicantuser());
            procInst.setFlastupdatedate(new Date()); //= DateTime.Now;
            procInst.setFlastupdateby(Instance.getCureentuser().getUserName()); //= procInstanceEntity.CureentUserID;
            procInst.setFprocinsname(Instance.getProcinsname());// = procInstanceEntity.GetFormDataXmlValue("Header_formSubTitle");
            procInst.setFprocinsno(Instance.getProcinsno());// = procInstanceEntity.GetFormDataXmlValue("Header_formNumber");
            Add(procInst, "add", "TappPorcessins");
//                procInstanceEntity.EmailVariable["ProcInsID"] = procInst.FID.ToString();
//                procInstanceEntity.EmailVariable["FFormInsID"] = formDataEntity.FID.ToString();
        } else {
            TappPorcessinsEntity procInst = tappPorcessinsDao.queryById(Instance.getProcinsid());// db.TB_WMP_ProcInstance.FirstOrDefault(ee => ee.FID == procInstanceEntity.ProcInsID && ee.FInactivateDate == null);
            if (procInst == null) {
                TappFromDataEntity formDataEntity = tappFromdataDao.queryById(procInst.getFid());
                formDataEntity.setFid(IdWorker.getId());
                Instance.setFforminsid(formDataEntity.getFid());
                formDataEntity.setFcreateby(Instance.getCureentuser().getUserName());// = procInstanceEntity.CureentUserID;
                formDataEntity.setFcreationdate(new Date()); ///= DateTime.Now;
                formDataEntity.setFromid(Instance.getFromid());
                formDataEntity.setFromdata(Instance.getFromdataJson());
                formDataEntity.setFlastupdateby(Instance.getCureentuser().getUserName());
                formDataEntity.setFlastupdatedate(new Date()); //= DateTime.Now;
                Add(formDataEntity, "add", "TappFromdata");
                procInst = new TappPorcessinsEntity();
                procInst.setFid(Instance.getProcinsid());
                procInst.setFcreateby(Instance.getCureentuser().getUserName());
                procInst.setFcreationdate(new Date());
                procInst.setFromdataid(formDataEntity.getFid());
                procInst.setFprocessid(Instance.getProcid());
                procInst.setFromid(Instance.getFromid());
                procInst.setFstarttime(new Date()); ///= DateTime.Now;
                procInst.setFstatus(status);
                procInst.setFstarter(Instance.getCureentuser().getUserName());// = procInstanceEntity.ApplicantUserNo;
                procInst.setFstartername(Instance.getCureentuser().getRealaname());
                procInst.setFapplicantuser(Instance.getApplicantuserno());
                procInst.setFapplicantusername(Instance.getApplicantuser());
                procInst.setFlastupdatedate(new Date()); //= DateTime.Now;
                procInst.setFlastupdateby(Instance.getCureentuser().getUserName()); //= procInstanceEntity.CureentUserID;
                procInst.setFprocinsname(Instance.getProcinsname());// = procInstanceEntity.GetFormDataXmlValue("Header_formSubTitle");
                procInst.setFprocinsno(Instance.getProcinsno());// = procInstanceEntity.GetFormDataXmlValue("Header_formNumber");
                Add(procInst, "add", "TappPorcessins");
            } else {
                //  procInst.FK2ProcInsID = -1;
                TappFromDataEntity formDataEntity = tappFromdataDao.queryById(procInst.getFromdataid());  ///db.TB_WMP_FormData.FirstOrDefault(ee => ee.FID == procInst.FFormInsID && ee.FInactivateDate == null);
                if (formDataEntity == null) {
                    formDataEntity = new TappFromDataEntity();
                    formDataEntity.setFid(IdWorker.getId());
                    Instance.setFforminsid(formDataEntity.getFid());
                    formDataEntity.setFcreateby(Instance.getCureentuser().getUserName());// = procInstanceEntity.CureentUserID;
                    formDataEntity.setFcreationdate(new Date()); ///= DateTime.Now;
                    Add(formDataEntity, "add", "TappFromdata");
                    formDataEntity.setFromid(Instance.getFromid());
                } else {
                    Add(formDataEntity, "edit", "TappFromdata");
                }
                formDataEntity.setFromdata(Instance.getFromdataJson());
                formDataEntity.setFlastupdateby(Instance.getCureentuser().getUserName()); //= procInstanceEntity.CureentUserID;
                formDataEntity.setFlastupdatedate(new Date());
                procInst.setFprocinsname(Instance.getProcinsname());
                procInst.setFprocinsno(Instance.getProcinsno());///FProcInsNO = procInstanceEntity.GetFormDataXmlValue("Header_formNumber");
                procInst.setFlastupdatedate(new Date()); //= DateTime.Now;
                procInst.setFlastupdateby(Instance.getCureentuser().getUserName());// = procInstanceEntity.CureentUserID;
                ///暂存不更改流程状态
                if (status != 1) {
                    procInst.setFstatus(status); //= status;
                }
                Add(procInst, "edit", "TappPorcessins");
                /// dataList.Add(new ApproveEntity { Entity = formDataEntity, OperationType = "edit", TableName = "TB_WMP_FormData" });
            }
        }
        Instance.addRunlog("保存流程实例，表单实例，审批记录，节点实例的状态更新成功！\r\n");
        return true;
    }

    /// <summary>
    /// 删除草稿
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    /// <returns></returns>
    public Boolean DelProcInst() {
        TappPorcessinsEntity porcessins = tappPorcessinsDao.queryById(Instance.getProcinsid());
        if (porcessins.getFstatus() == 0 && (porcessins.getFstarter().equals(Instance.getCureentuser()) || porcessins.getFapplicantuser().equals(Instance.getCureentuser()))) {
            Add(porcessins, "del", "TappPorcessins");
            return SaveData();
        } else {
            Instance.addErrorlog("该流程已经不是草稿状态，或者您没有权限删除！");
            return false;
        }

    }

    /// <summary>
    /// 转办
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    /// <returns></returns>
    public Boolean TransferProcInst(TappActinsEntity tappActins) {
        SaveProcInstData(2);
        tappActins.setFprocessinsid(Instance.getProcinsid());
        tappActins.setFstatus(1);
        tappActins.setFapproversuser(Instance.getRedrituser());
        tappActins.setFlastupdateby(Instance.getCureentuser().getUserName());
        tappActins.setFlastupdatedate(new Date());
        Add(tappActins, "edit", "TappActins");
//        EmailHelper emial = new EmailHelper(procInstanceEntity, null, dataList);
//        emial.SendDoReadEmial();

        return SaveData();
    }

    /// <summary>
    /// 暂存使用
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    /// <returns></returns>
    public Boolean TempSave() {
        SaveProcInstData(1);
        return SaveData();
    }

    /// <summary>
    /// 撤销,废弃，终止入口
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    ///  <param name="Action">5 废弃 6 撤销 4终止</param>
    /// <returns></returns>
    public Boolean OperationProcInst(int Action) {
        return true;
    }

    @Transactional
    public Boolean SaveData() {
        int procInsStatus = 0;
        for (int i = 0; i < dataList.size(); i++) {
            ApproveEntity approveEntity = dataList.get(i);
            switch (approveEntity.getTablename()) {
                case "TappFromdata":
                    TappFromDataEntity tappFromdata = null;
                    if (approveEntity.getOperationtype().equals("add")) {
                        tappFromdata = (TappFromDataEntity) approveEntity.getEntity();
                        tappFromdataDao.insert(tappFromdata);
                    } else if (approveEntity.getOperationtype().equals("edit")) {
                        tappFromdata = (TappFromDataEntity) approveEntity.getEntity();
                        tappFromdataDao.updateById(tappFromdata);
                    } else {
                        tappFromdata = (TappFromDataEntity) approveEntity.getEntity();
                        tappFromdataDao.deleteById(tappFromdata.getFid());
                    }
                    break;
                case "TappPorcessins":
                    TappPorcessinsEntity tappPorcessins = null;
                    if (approveEntity.getOperationtype().equals("add")) {
                        tappPorcessins = (TappPorcessinsEntity) approveEntity.getEntity();
                        if (isHandled) {
                            if (IsFlowEnd) {
                                tappPorcessins.setFcurrentactname("");
                                tappPorcessins.setFcurrentapproversuser("");
                                tappPorcessins.setFcompletetime(new Date());
                                tappPorcessins.setFstatus(4);
                            } else {
                                tappPorcessins.setFcurrentactname(Instance.getNexact().getFactname());
                                tappPorcessins.setFcurrentapproversuser(String.join(",", userList));
                            }
                        }
                        tappPorcessinsDao.insert(tappPorcessins);
                    } else if (approveEntity.getOperationtype().equals("edit")) {
                        tappPorcessins = (TappPorcessinsEntity) approveEntity.getEntity();
                        if (isHandled) {
                            if (IsFlowEnd) {
                                tappPorcessins.setFcurrentactname("");
                                tappPorcessins.setFcurrentapproversuser("");
                                tappPorcessins.setFcompletetime(new Date());
                                //  tappPorcessins.setFromdataid(tappFromdata.getFid());
                                tappPorcessins.setFstatus(4);
                            } else {
                                tappPorcessins.setFcurrentactname(Instance.getNexact().getFactname());
                                tappPorcessins.setFcurrentapproversuser(String.join(",", userList));
                            }
                        }
                        tappPorcessinsDao.updateById(tappPorcessins);
                    } else {
                        tappPorcessinsDao.deleteById(((TappPorcessinsEntity) approveEntity.getEntity()).getFid());
                    }
                    break;
                case "TappActinscommunicate":
                    if (approveEntity.getOperationtype().equals("add")) {
                        TappActinsCommunicateEntity tappActinscommunicate = (TappActinsCommunicateEntity) approveEntity.getEntity();
                        tappActinscommunicateDao.insert(tappActinscommunicate);
                    } else if (approveEntity.getOperationtype().equals("edit")) {
                        tappActinscommunicateDao.updateById((TappActinsCommunicateEntity) approveEntity.getEntity());
                    } else {
                        tappActinscommunicateDao.deleteById(((TappActinsCommunicateEntity) approveEntity.getEntity()).getFid());
                    }
                    break;
                case "TappActins":
                    if (approveEntity.getOperationtype().equals("add")) {
                        TappActinsEntity tappActins = (TappActinsEntity) approveEntity.getEntity();
                        tappActins.setFprocessinsid(Instance.getProcinsid());
                        tappActinsService.insert(tappActins);
                    } else if (approveEntity.getOperationtype().equals("edit")) {
                        tappActinsService.updateById((TappActinsEntity) approveEntity.getEntity());
                    } else {
                        tappActinsService.deleteById(((TappActinsEntity) approveEntity.getEntity()).getFid());
                    }
                    break;
                case "TappProcaudit":
                    if (approveEntity.getOperationtype() == "add") {
                        tappProcauditDao.insert((TappProcAuditEntity) approveEntity.getEntity());
                    } else if (approveEntity.getOperationtype() == "edit") {
                        tappProcauditDao.updateById((TappProcAuditEntity) approveEntity.getEntity());
                    } else {
                        tappProcauditDao.deleteById(((TappProcAuditEntity) approveEntity.getEntity()).getFid());
                    }
                    break;
            }
        }
        for (int i = 0; i < Instance.getTappProcauditList().size(); i++) {
            TappProcAuditEntity tappProcaudit = Instance.getTappProcauditList().get(i);
            tappProcaudit.setFprocinsid(Instance.getProcinsid());
            tappProcauditDao.insert(tappProcaudit);
        }

        return true;


    }

    /// <summary>
    ///跳转
    /// </summary>
    public Boolean SkipProcInst() {

        return true;
    }

    /// <summary>
    /// 抄送入口
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    ///  <returns></returns>
    public Boolean CCProcInst(TappActinsEntity tappActins) {
        List<String> ccuserList = new ArrayList<>();
        Map<String, String> mapParam = new HashMap<>();
        if (Instance.copylist != null && Instance.copylist.size() > 0) {
            //added by zhong 去掉重复用户
            for (CopyUserEntity copyuseritem : Instance.copylist
            ) {
                if (!ccuserList.contains(copyuseritem.getNo())) {
                    ccuserList.add(copyuseritem.getNo());
                    mapParam.put(copyuseritem.getNo(), copyuseritem.getName());
                }
            }
        }
        List<String> copySendUser = new ArrayList<>();
        List<String> copySendUserName = new ArrayList<>();
        String msg = "";
        for (String item : ccuserList) {
            String UserName = mapParam.get(item);// CacheHelper.Instance.GetUserNameAll(item);
            TappActinsCommunicateEntity tappActinscommunicate = new TappActinsCommunicateEntity();
            tappActinscommunicate.setFactinsid(Instance.getActinsid());
            tappActinscommunicate.setFapproversuser(item);
            tappActinscommunicate.setFcommunicatetype(6);
            tappActinscommunicate.setFstatus(1);
            List<TappActinsCommunicateEntity> tappActinscommunicateList = tappActinscommunicateDao.queryAll(tappActinscommunicate);
            if (!(tappActinscommunicateList.isEmpty() || tappActinscommunicateList.size() == 0)) {
                msg += UserName + "[" + item + "]、";
            } else {
                copySendUser.add(item);
                copySendUserName.add(UserName);
            }
        }
        if (!copySendUser.isEmpty()) {
            for (int i = 0; i < copySendUser.size(); i++) {
                TappActinsCommunicateEntity aice = new TappActinsCommunicateEntity();
                aice.setFactinsid(Instance.getActinsid()); //= procInstanceEntity.ActInsID;
                aice.setFprocessinsid(Instance.getProcinsid());
                // aice.FActID = ActInsEntity.FActID;
                aice.setFactname(Instance.getCurrentactentity().getFactname());//FActName = ActInsEntity.FActName;
                // aice.FActDisplayName = ActInsEntity.FActDisplayName;
                aice.setFcommunicatetype(6); //= 6;
                aice.setFapproversuser(copySendUser.get(i));/// copySendUser[i].Trim().Replace("\n", "").Replace("\t", "").Replace("\r", "");

                aice.setFstatus(1);
                aice.setFcreateby(Instance.getCureentuser().getUserName());
                aice.setFcreationdate(new Date()); //= DateTime.Now;
                aice.setFlastupdateby(Instance.getCureentuser().getUserName()); //= procInstanceEntity.CureentUserID;
                aice.setFcreationdate(new Date());
                Add(aice, "add", "TappActinscommunicate");
            }
            ///创建待办待阅信息 抄送邮件，待办待阅邮件，流程结束邮件
            String bark = "【" + Instance.getCureentuser().getRealaname() + " 抄送给：";
            bark = bark + String.join("、", copySendUserName);
            bark += "】" + "备注:" + Instance.getApprovedDes();
            TappProcAuditEntity procAudi = new TappProcAuditEntity();
            procAudi.setFprocinsid(Instance.getProcinsid()); //procInstanceEntity.ProcInsID.Value;
            procAudi.setFactinsid(Instance.getActinsid());
            procAudi.setFactname(Instance.getCurrentactentity().getFactname());
            procAudi.setFapprovelaction(Instance.getActionname());
            procAudi.setFapproveldescr(bark);
            //发起沟通或者抄送时，开始时间为当前时间；回复沟通时，开始时间为到达日期；
            procAudi.setFactcreatedate(new Date());
            procAudi.setFactopendate(new Date());
            procAudi.setFactfishdate(new Date());
            procAudi.setFapproversname(Instance.getCureentuser().getUserName());
            procAudi.setFcreateby(Instance.getCureentuser().getUserName());
            procAudi.setFcreationdate(new Date());
            procAudi.setFlastupdatedate(new Date());

            Add(procAudi, "add", "TappProcaudit");
            ///发送邮件 和审批记录
            //        EmailHelper emial = new EmailHelper(procInstanceEntity, null, dataList);
//        emial.SendCCEmial(procInstanceEntity.RedritUser);
            return SaveData();
        } else {
            if (!msg.equals("")) {
                Instance.addErrorlog("重复抄送人员：" + msg);
                return false;
            }
            return true;
        }

    }

    /// <summary>
    /// 取消沟通
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    /// <returns></returns>
    public Boolean CancerCommunication() {
        TappActinsCommunicateEntity tappActinscommunicate = new TappActinsCommunicateEntity();
        tappActinscommunicate.setFactinsid(Instance.getActinsid());
        tappActinscommunicate.setFcommunicatetype(5);
        List<TappActinsCommunicateEntity> tappActinscommunicateList = tappActinscommunicateDao.queryAll(tappActinscommunicate);
        if (!tappActinscommunicateList.isEmpty()) {
            for (TappActinsCommunicateEntity item : tappActinscommunicateList) {
                Add(item, "del", "TappActinscommunicate");
            }

        }
        TappActinsEntity tappActins = tappActinsService.queryById(Instance.getActinsid());
        tappActins.setFstatus(1);
        Add(tappActins, "edit", "TappActins");
        Instance.getTappPorcessins().setFstatus(2);
        Add(Instance.getTappPorcessins(), "edit", "TappPorcessins");
        return SaveData();
    }

    /// <summary>
    /// 发起沟通
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    /// <returns></returns>
    public Boolean StartCommunication() {
//        String users = Instance.getApprovalobject().replace(';', ',');
//        String[] strUser = users.split(",");
        List<String> ccuserList = new ArrayList<>();
        if (Instance.copylist != null && Instance.copylist.size() > 0) {
            //added by zhong 去掉重复用户
            for (CopyUserEntity copyuseritem : Instance.copylist
            ) {
                if (!userList.contains(copyuseritem.getNo())) {
                    ccuserList.add(copyuseritem.getNo());
                }
            }
        }
        List<String> copySendUser = new ArrayList<>();
        List<String> copySendUserName = new ArrayList<>();
        String msg = "";
        for (String item : ccuserList) {
            String UserName = "";// CacheHelper.Instance.GetUserNameAll(item);
            TappActinsCommunicateEntity tappActinscommunicate = new TappActinsCommunicateEntity();
            tappActinscommunicate.setFactinsid(Instance.getActinsid());
            tappActinscommunicate.setFapproversuser(item);
            tappActinscommunicate.setFcommunicatetype(6);
            tappActinscommunicate.setFstatus(1);
            List<TappActinsCommunicateEntity> tappActinscommunicateList = tappActinscommunicateDao.queryAll(tappActinscommunicate);
            if (!(tappActinscommunicateList.isEmpty() || tappActinscommunicateList.size() == 0)) {
                msg += UserName + "[" + item + "]、";
            } else {
                copySendUser.add(item);
                copySendUserName.add(UserName);
            }
        }
        TappActinsCommunicateEntity tappActinscommunicate = new TappActinsCommunicateEntity();
        tappActinscommunicate.setFactinsid(Instance.getActinsid());
        tappActinscommunicate.setFcommunicatetype(5);
        tappActinscommunicate.setFstatus(1); //等于1 未回复 等于2 已回复
        List<TappActinsCommunicateEntity> tappActinscommunicateList = tappActinscommunicateDao.queryAll(tappActinscommunicate);
        if (tappActinscommunicateList.isEmpty()) {
            for (int i = 0; i < copySendUser.size(); i++) {
                TappActinsCommunicateEntity aice = new TappActinsCommunicateEntity();
                aice.setFactinsid(Instance.getActinsid());
                aice.setFprocessinsid(Instance.getProcinsid());
                aice.setFactname(Instance.getCurrentactentity().getFactname());
                aice.setFcommunicatetype(5);
                aice.setFapproversuser(copySendUser.get(i));
                aice.setFstatus(1);
                aice.setFcreateby(Instance.getCureentuser().getUserName());
                aice.setFcreationdate(new Date());
                aice.setFlastupdateby(Instance.getCureentuser().getUserName());
                aice.setFlastupdatedate(new Date());
                Add(aice, "add", "TappActinscommunicate");
            }
            TappActinsEntity actInsEntity = tappActinsService.queryById(Instance.getActinsid());
            if (actInsEntity != null) {
                actInsEntity.setFstatus(0);
                actInsEntity.setFlastupdateby(Instance.getCureentuser().getUserName());
                actInsEntity.setFlastupdatedate(new Date());
                Add(actInsEntity, "edit", "TappActins");
            }
            Instance.getTappPorcessins().setFstatus(2);
            Add(Instance.getTappPorcessins(), "edit", "TappPorcessins");
//            ///发送沟通邮件
//            EmailHelper emial = new EmailHelper(procInstanceEntity, null, dataList);
//            emial.LaunchCommunicationEmail(procInstanceEntity, CacheHelper.Instance.GetUserName(procInstanceEntity.CureentUserID));
            return SaveData();
        } else {
            Instance.addErrorlog("请勿重复发起沟通！");
            return false;

        }
    }

    /// <summary>
    /// 回复沟通
    /// </summary>
    /// <param name="procInstanceEntity">处理流程数据对象 包含当前节点信息，当前流程实例信息，表单信息等等</param>
    /// <returns></returns>
    public Boolean AnswerCommunication() {
        TappActinsCommunicateEntity tappActinscommunicate = new TappActinsCommunicateEntity();
        tappActinscommunicate.setFactinsid(Instance.getActinsid());
        tappActinscommunicate.setFcommunicatetype(5);
        tappActinscommunicate.setFstatus(1);
        List<TappActinsCommunicateEntity> tappActinscommunicateList = tappActinscommunicateDao.queryAll(tappActinscommunicate);
        if (!tappActinscommunicateList.isEmpty()) {
            Integer idex = 0;
            for (TappActinsCommunicateEntity item : tappActinscommunicateList) {
                if (item.getFapproversuser().equals(Instance.getCureentuser().getUserName())) {
                    item.setFstatus(2);
                    item.setFcompleteddate(new Date());
                    item.setFlastupdatedate(new Date());
                    item.setFlastupdateby(Instance.getCureentuser().getUserName());
                    Add(item, "edit", "TappActinscommunicate");
                } else {
                    idex++;
                }
            }
            if (idex == 0) {
                TappActinsEntity tappActins = tappActinsService.queryById(Instance.getActinsid());
                tappActins.setFstatus(1);
                tappActins.setFlastupdatedate(new Date());
                tappActins.setFlastupdateby(Instance.getCureentuser().getUserName());
                Add(tappActins, "edit", "TappActins");
            }
            Instance.getTappPorcessins().setFstatus(2);
            Add(Instance.getTappPorcessins(), "edit", "TappPorcessins");
            return SaveData();
        } else {
            Instance.addErrorlog("可能已经沟通过了！");
            return false;
        }

    }
}
